package edu.ipccenter.toster.ejb;

//import com.sun.xml.ws.api.tx.at.Transactional;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashSet;

import edu.ipccenter.toster.Name;
import edu.ipccenter.toster.TestCase;
import edu.ipccenter.toster.TestCaseUtils;
import edu.ipccenter.toster.jpa.JPATestCase;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.ManagedBean;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;


@Stateless(name="TestCaseUtils")
//@Transactional
@TransactionAttribute(TransactionAttributeType.REQUIRED )
public class TestCaseUtilsBean implements TestCaseUtils {
        
        
	private Collection<TestCase> testCases = new HashSet<TestCase>();
        @PersistenceContext(unitName="TosterPU")
        private EntityManager em;

           
      
        
        /**
         * This method finds TestCase object in the database, using it's id
         * @param id
         * @return 
         */
	@Override
        public TestCase findByID(BigInteger id) {
            TestCase test = null;  
       
        List<JPATestCase> testcase;
        Query q = em.createQuery("select c from JPATestCase c where c.tcId =:myid");
        q.setParameter("myid", id);
        testcase = q.getResultList();
        if (testcase.isEmpty()) {
            return new TestCaseBean(); //просто объект
        }
        
        InitialContext ic;
        try {
            ic = new InitialContext();
            test = (TestCase) ic.lookup("java:global/Tost/Tost-ejb/TestCase");
        } catch (NamingException ex) {
            Logger.getLogger(TestCaseUtilsBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
           
        JPATestCase jtest = testcase.get(0);
        System.out.println(""+jtest.getThemes());
        test.setTestCase(jtest);       
         
        return test;
        }

        /**
         * This method create the element of TestCase and persist information in
         * the database as JPATestCase object
         * @param name
         * @param description
         * @param content
         * @return 
         */
	@Override
	public TestCase create(String name, String description, String content) {
            
         
		TestCase test = null;
	InitialContext ic;
        try {
            ic = new InitialContext();
            test = (TestCase) ic.lookup("java:global/Tost/Tost-ejb/TestCase");
        } catch (NamingException ex) {
            Logger.getLogger(TestCaseUtilsBean.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
                
                JPATestCase jtc = new JPATestCase();
                jtc.setTcName(name);
                jtc.setTcContent(content);
                jtc.setDescription(description);
                em.merge(jtc);
                test.setTestCase(jtc);
		
		
      		return test;
	}

        /**
         * This method finds all TestCases by theme id, just return Collection<Name> object
         * @param id
         * @return result if there are exist TestCases corresponding current Theme_id
         * @return null result if there aren't exist TestCases corresponding current Theme_id
         */
	@Override
	public Collection<Name> findByTheme(BigInteger id) {
		Query q = em.createQuery("select c1 from JPATestCase c1, JPATheme c2 where c1.tcId = :themeId");
                q.setParameter("themeId", id);
                
                List<JPATestCase> jlisttest = q.getResultList();
                if(jlisttest==null) return null;
                
                Collection<Name> result = new HashSet<Name>();
               
                
                for(int i=0; i<jlisttest.size(); i++){
                    Name nameRes = new Name();
                    nameRes.setID(jlisttest.get(i).getTcId());
                    nameRes.setName(jlisttest.get(i).getTcName());
                    result.add(nameRes);
                }
                
		return result;
	}

        /**
         * This method finds by name using oracle construction LIKE
         * @param keyText
         * @param upperLimit
         * @return 
         */
	@Override
	public Collection<Name> findByName(String keyText, int upperLimit) {//???
		Collection<Name> names = new HashSet<Name>();
		
                Query q = em.createQuery("select c from JPATestCase c where c.tcName LIKE :keyText");
                q.setParameter("keyText", '%'+keyText+'%');
                
                List<JPATestCase> jtest =(List<JPATestCase>) q.getResultList();
                
                for(int i = 0; i<jtest.size() && i< upperLimit; i++){
                    Name n = new Name();
                    n.setID(jtest.get(i).getTcId());
                    n.setName(jtest.get(i).getTcName());
                    names.add(n);
                }
                               
                
		return names;
	}
}
